import Taro from '@tarojs/taro'
import { orderService } from '../services/order'
import type { PaymentResponse } from '../types/api'

interface WechatPayParams {
  timeStamp: string
  nonceStr: string
  package: string
  signType: string
  paySign: string
}

export class WechatPayManager {
  async pay(orderId: string): Promise<boolean> {
    try {
      const paymentData = await orderService.createPayment({
        orderId,
        paymentMethod: 'wechat'
      })

      const payParams = this.formatPayParams(paymentData)
      
      return await this.callWechatPay(payParams)
    } catch (error: any) {
      Taro.showToast({
        title: error.message || '支付失败',
        icon: 'none'
      })
      return false
    }
  }

  private formatPayParams(paymentData: PaymentResponse): WechatPayParams {
    return {
      timeStamp: paymentData.timeStamp,
      nonceStr: paymentData.nonceStr,
      package: `prepay_id=${paymentData.prepayId}`,
      signType: paymentData.signType,
      paySign: paymentData.paySign
    }
  }

  private async callWechatPay(params: WechatPayParams): Promise<boolean> {
    return new Promise((resolve) => {
      Taro.requestPayment({
        ...params,
        success: () => {
          Taro.showToast({
            title: '支付成功',
            icon: 'success'
          })
          resolve(true)
        },
        fail: (error: any) => {
          if (error.errMsg?.includes('cancel')) {
            Taro.showToast({
              title: '支付已取消',
              icon: 'none'
            })
          } else {
            Taro.showToast({
              title: '支付失败',
              icon: 'none'
            })
          }
          resolve(false)
        }
      })
    })
  }

  async checkPaymentStatus(orderId: string): Promise<'paid' | 'pending' | 'failed'> {
    try {
      const result = await orderService.queryPaymentStatus(orderId)
      return result.status
    } catch (error) {
      return 'failed'
    }
  }

  async waitForPaymentComplete(orderId: string, maxWaitTime: number = 30000): Promise<boolean> {
    const startTime = Date.now()
    const checkInterval = 2000

    return new Promise((resolve) => {
      const timer = setInterval(async () => {
        const elapsedTime = Date.now() - startTime
        
        if (elapsedTime >= maxWaitTime) {
          clearInterval(timer)
          resolve(false)
          return
        }

        const status = await this.checkPaymentStatus(orderId)
        
        if (status === 'paid') {
          clearInterval(timer)
          resolve(true)
        } else if (status === 'failed') {
          clearInterval(timer)
          resolve(false)
        }
      }, checkInterval)
    })
  }
}

export const wechatPay = new WechatPayManager()
export default wechatPay